#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
API测试脚本
"""

import requests
import json

# API基础URL
BASE_URL = "http://127.0.0.1:8000"

def test_api_endpoints():
    """测试API端点"""
    print("开始测试API端点...")
    
    try:
        # 1. 测试健康检查
        print("\n1. 测试健康检查...")
        response = requests.get(f"{BASE_URL}/health")
        print(f"健康检查: {response.status_code} - {response.json()}")
        
        # 2. 测试获取热点列表
        print("\n2. 测试获取热点列表...")
        response = requests.get(f"{BASE_URL}/api/v1/trends/", params={"limit": 3})
        print(f"热点列表: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"获取到 {data['total']} 个热点")
            for item in data['data']:
                print(f"  - [{item['source']}] {item['title']}")
        
        # 3. 测试获取数据源列表
        print("\n3. 测试获取数据源列表...")
        response = requests.get(f"{BASE_URL}/api/v1/trends/sources")
        print(f"数据源列表: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print("可用数据源:")
            for source in data['sources']:
                print(f"  - {source['key']}: {source['name']}")
        
        # 4. 测试获取生成的内容列表
        print("\n4. 测试获取生成的内容列表...")
        response = requests.get(f"{BASE_URL}/api/v1/content/", params={"limit": 3})
        print(f"内容列表: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"获取到 {data['total']} 个生成内容")
            for item in data['data']:
                print(f"  - [{item['platform']}] {item['content'][:50]}...")
        
        # 5. 测试使用通义千问生成内容
        print("\n5. 测试使用通义千问生成内容...")
        # 先获取一个热点ID
        response = requests.get(f"{BASE_URL}/api/v1/trends/", params={"limit": 1})
        if response.status_code == 200 and response.json()['total'] > 0:
            trend_id = response.json()['data'][0]['id']
            print(f"选择热点 ID: {trend_id}")
            
            # 生成内容
            generate_data = {
                "trend_id": trend_id,
                "platforms": ["weibo"],
                "style": "default",
                "generator": "qwen"
            }
            
            response = requests.post(f"{BASE_URL}/api/v1/content/generate", json=generate_data)
            print(f"内容生成: {response.status_code}")
            if response.status_code == 200:
                data = response.json()
                print(f"生成结果: {data['status']}")
                if data['status'] == 'completed':
                    for platform, result in data['results'].items():
                        if result['status'] == 'success':
                            print(f"  - {platform}: 成功生成内容 ({len(result['content']['text'])} 字符)")
        
        print("\n🎉 API测试完成!")
        
    except Exception as e:
        print(f"❌ API测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_api_endpoints()